using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Net;

namespace Departure
{
    class RequestThread
    {
        ContainerControl m_sender = null;

        Delegate m_senderDelegate = null;

        string m_URL = "";
        string m_additionalHeader = "";
        string m_UserAgent = "";

        public RequestThread(ContainerControl sender, Delegate senderDelegate, string URL, string UserAgent, string additionalHeader)
		{
			m_sender = sender;
			m_senderDelegate = senderDelegate;
            m_URL = URL;
            m_additionalHeader = additionalHeader;

		}

		/// <summary>
		/// Method for ThreadStart delegate
		/// </summary>
		public void RunProcess()
		{
			Thread.CurrentThread.IsBackground = true; //make them a daemon
			LocalRunProcess();
		}

		/// <summary>
		/// Local Method for the actual work.
		/// </summary>
        private void LocalRunProcess()
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_URL);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.KeepAlive = true;
                request.Method = "GET";

                if (m_UserAgent != "")
                    request.UserAgent = m_UserAgent;
                
                if (m_additionalHeader != "")
                    request.Headers.Add(m_additionalHeader);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());

                string source = sr.ReadToEnd();

                sr.Close();
                
                m_sender.BeginInvoke(m_senderDelegate, new object[] { source, false });
            }
            catch (Exception ex)
            {
                m_sender.BeginInvoke(m_senderDelegate, new object[] { ex.Message, true });
            }
        }
    }
}
